import { query, create, remove, update } from '../services/sysPermission';
import createModel, { delay } from './base';

const baseVersion = {
	permissionKey: null,
	permissionName: null,
	icon: null,
	uri: null,
	permissionType: null,
	sort: 1,
	versionName: '123',
	versionCode: '123'
};

export default createModel({
	namespace: 'sysPermission',
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				if (location.pathname === '/sysPermission') { // 每次刷新一下，获取最新
					dispatch({
						type: 'query'
					});
				}
			});
		},
	},
	effects: {
		*deleteAndRefresh({ id }, { put }) {
			yield put({ type: 'delete', id });
			yield put({ type: 'app/query' });
		},
		*createAndRefresh({ payload }, { put }) {
			yield put({ type: 'create', payload });
			yield delay(5000);
			yield put({ type: 'sysPermission/query' });
			yield put({ type: 'app/query' });
		},
		*updateAndRefresh({ payload }, { put }) {
			yield put({ type: 'update', payload });
			yield delay(5000);
			yield put({ type: 'sysPermission/query' });
		}
	},
	reducers: {
		updateOne(state, { payload }) {
			const { versions, ...data } = payload;

			const addList = [];
			versions.forEach(v => {
				if (v.id) {
					const t = state.list.find(p => p.id === v.id);
					if (t) addList.push({ ...t, ...v });
				} else {
					addList.push({ ...baseVersion, ...v, id: Math.random(), pPermissionId: data.id });
				}
			});
			const list = state.list.map(t => t.id === data.id ? { ...t, ...data } : t);
			return { ...state, list: list.concat(addList), currentItem: null };
		},
	}
}, query, create, remove, update);
